package edu.washington.cs.pomdb.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Semaphore;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

/**
 * @author Yanping Huang
 *
 */

public class LoginWindow extends JFrame{
	/**
	 * 
	 */
	private static final long serialVersionUID = 201202280726L;
	private JButton b1;
	private JLabel l1; 
	private JTextField t1;
	private JPanel contentPane;
	private String userName;
	private Semaphore semaphore;


	public String getUserName(){
		try {
			semaphore.acquire();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userName;
	}

	private void login_actionPerformed(ActionEvent e){
		userName = new String(t1.getText());
		if(userName.equals("") ){ //if login name is empty
			b1.setEnabled(false);
			JLabel errorFields = new JLabel("<HTML><FONT COLOR = Red>You must enter a username to login.</FONT></HTML>");	
			JOptionPane.showMessageDialog(null,errorFields); 
			t1.setText("");
			b1.setEnabled(true);
			this.setVisible(true);
		}else{
			b1.setEnabled(false);   // Set button enable to false to prevent 2 login attempts
			this.dispose();
			semaphore.release();
		}
	}



	private void createAndShowGUI(){
		b1 = new JButton("Login");
		l1 = new JLabel();
		t1 = new JTextField();
		l1.setText("User Name:");
		contentPane = (JPanel)this.getContentPane();

		b1.setText("Login");
		b1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){
				login_actionPerformed(e);
			}

		});

		contentPane.setLayout(null);
		contentPane.setBorder(BorderFactory.createEtchedBorder());
		contentPane.setBackground(new Color(204, 204, 204));
		GUI.addComponent(contentPane, l1, 25,10,75,40);
		GUI.addComponent(contentPane, t1, 105,10,200,40);
		GUI.addComponent(contentPane, b1, 108,70,120,40);
		//
		// login
		//
		this.setTitle("Login");
		this.setLocation(new Point(200, 200));
		this.setSize(new Dimension(336, 141));

		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		this.setResizable(false);
		this.setVisible(true);
	}

	

	public LoginWindow(){
		super();
		semaphore = new Semaphore(0);
		try {
			javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
				public void run() {
					createAndShowGUI();
				}
			});
		} catch (Exception e) { 
			System.err.println("loginWindow.createGUI didn't successfully complete");
		}
	}


}
